{% extends 'myadmin/base.html' %}
{% block main_body %}
<style>
    .form-card {
        background: #fff;
        border-radius: 6px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        padding: 20px;
    }
    .form-section {
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #f1f1f1;
    }
    .form-row {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10px;
    }
    .form-col {
        flex: 1;
        min-width: 300px;
        padding: 0 10px;
        box-sizing: border-box;
    }
    .form-group {
        margin-bottom: 12px;
        width: 100%;
    }
    .form-group label {
        font-weight: 600;
        font-size: 13px;
        margin-bottom: 5px;
        display: block;
    }
    .form-control {
        width: 100%;
        padding: 6px 10px;
        font-size: 13px;
        height: 34px;
        box-sizing: border-box;
    }
    textarea.form-control {
        height: auto;
        min-height: 100px;
    }
    .radio-group {
        display: flex;
        gap: 15px;
        margin-top: 8px;
        flex-wrap: wrap;
    }
    .radio-item {
        display: flex;
        align-items: center;
        gap: 5px;
    }
    .btn-group {
        margin-top: 15px;
        display: flex;
        gap: 10px;
        justify-content: flex-end;
    }
    .required-mark {
        color: #dd4b39;
        margin-left: 3px;
    }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const contentTextarea = document.querySelector('textarea[name="content"]');
        const previewContainer = document.createElement('div');
        previewContainer.classList.add('content-preview');
        contentTextarea.insertAdjacentElement('afterend', previewContainer);
        // 时间格式处理
        const timeInput = document.querySelector('input[name="recommendation_time"]');
        const form = document.querySelector('form');
        
        // 页面加载时：将数据库时间转换为datetime-local格式（含T分隔符）
        if (timeInput.value) {
            const dbTime = timeInput.value; // 格式：YYYY-MM-DD HH:mm:ss
            const formattedTime = dbTime.replace(' ', 'T'); // 转为：YYYY-MM-DDThh:mm:ss
            timeInput.value = formattedTime;
        }
        
        // 提交时：确保表单正确转换格式（兼容未转换的情况）
        if (form && timeInput) {
            form.addEventListener('submit', function(e) {
                if (timeInput.value) {
                    // 若仍含T则替换为空格
                    timeInput.value = timeInput.value.replace('T', ' ');
                }
            });
        }

        function updatePreview() {
            const content = contentTextarea.value;
            const recommendationType = document.querySelector('select[name="recommendation_type"]').value;
            previewContainer.innerHTML = '';
            try {
                const data = JSON.parse(content);
                if (recommendationType === '饮食计划') {
                    if (data.plan_name) {
                        const planNameDiv = document.createElement('div');
                        planNameDiv.textContent = `计划名称：${data.plan_name}`;
                        previewContainer.appendChild(planNameDiv);
                    }
                    if (data.meals && Array.isArray(data.meals)) {
                        data.meals.forEach(meal => {
                            if (meal.type && meal.foods && Array.isArray(meal.foods)) {
                                const mealTypeDiv = document.createElement('div');
                                mealTypeDiv.textContent = `餐次：${meal.type}`;
                                previewContainer.appendChild(mealTypeDiv);

                                const foodList = document.createElement('ul');
                                meal.foods.forEach(food => {
                                    const foodItem = document.createElement('li');
                                    foodItem.textContent = `${food.name}：${food.quantity}g`;
                                    foodList.appendChild(foodItem);
                                });
                                previewContainer.appendChild(foodList);
                            }
                        });
                    }
                } else if (recommendationType === '食物推荐') {
                    if (data.recommendations && Array.isArray(data.recommendations)) {
                        data.recommendations.forEach(recommendation => {
                            const recommendationDiv = document.createElement('div');
                            recommendationDiv.textContent = `食物：${recommendation.food}，原因：${recommendation.reason}`;
                            previewContainer.appendChild(recommendationDiv);
                        });
                    }
                } else if (recommendationType === '食谱') {
                    if (data.recipe_name) {
                        const recipeNameDiv = document.createElement('div');
                        recipeNameDiv.textContent = `食谱名称：${data.recipe_name}`;
                        previewContainer.appendChild(recipeNameDiv);
                    }
                    if (data.ingredients && Array.isArray(data.ingredients)) {
                        const ingredientList = document.createElement('ul');
                        data.ingredients.forEach(ingredient => {
                            const ingredientItem = document.createElement('li');
                            ingredientItem.textContent = `${ingredient.name}：${ingredient.quantity}g`;
                            ingredientList.appendChild(ingredientItem);
                        });
                        previewContainer.appendChild(ingredientList);
                    }
                }
            } catch (error) {
                // 如果解析失败，原样展示
                const originalContentDiv = document.createElement('div');
                originalContentDiv.textContent = `原内容：${content}`;
                previewContainer.appendChild(originalContentDiv);
            }
        }

        // 初始加载时更新预览
        updatePreview();
        // 监听文本框内容变化，实时更新预览
        contentTextarea.addEventListener('input', updatePreview);
        // 监听推荐类型变化，实时更新预览
        document.querySelector('select[name="recommendation_type"]').addEventListener('change', updatePreview);
    });
</script>

<section class="content-header">
    <h1>推荐管理 <small>编辑推荐记录</small></h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-home"></i> 首页</a></li>
        <li><a href="#">推荐管理</a></li>
        <li class="active">编辑推荐记录</li>
    </ol>
</section>

<section class="content">
    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">编辑推荐记录</h3>
                </div>
                <form method="post" action="{% url 'myadmin_recommendations_update' record.recommendation_id %}" class="form-card">
                    {% csrf_token %}
                    
                    <!-- 基础信息 -->
                    <div class="form-section">
                        <h4><i class="fa fa-info-circle"></i> 推荐基本信息</h4>
                        <div class="form-row">
                            <div class="form-col">
                                <div class="form-group">
                                    <label>记录ID</label>
                                    <input type="text" value="{{ record.recommendation_id }}" class="form-control" disabled>
                                </div>
                                <div class="form-group">
                                    <label>用户 <span class="required-mark">*</span></label>
                                    <select name="user_id" class="form-control" required>
                                        {% for user in users %}
                                        <option value="{{ user.user_id }}" {% if record.user_id == user.user_id %}selected{% endif %}>
                                            {{ user.username }} (ID: {{ user.user_id }})
                                        </option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>推荐类型 <span class="required-mark">*</span></label>
                                    <select name="recommendation_type" class="form-control" required>
                                        {% for type in type_choices %}
                                        <option value="{{ type.0 }}" {% if record.recommendation_type == type.0 %}selected{% endif %}>
                                            {{ type.1 }}
                                        </option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>推荐依据 <span class="required-mark">*</span></label>
                                    <select name="based_on" class="form-control" required>
                                        {% for based in based_choices %}
                                        <option value="{{ based.0 }}" {% if record.based_on == based.0 %}selected{% endif %}>
                                            {{ based.1 }}
                                        </option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                            <div class="form-col">
                                <div class="form-group">
                                    <label>推荐时间</label>
                                    <input type="datetime-local" name="recommendation_time" 
                                           value="{{ record.recommendation_time|date:'Y-m-d H:i:s' }}" 
                                           class="form-control">
                                </div>
                                <div class="form-group">
                                    <label>接受状态</label>
                                    <div class="radio-group">
                                        <div class="radio-item">
                                            <input type="radio" name="is_accepted" id="acceptedTrue" value="True" 
                                                {% if record.is_accepted == True %}checked{% endif %}>
                                            <label for="acceptedTrue">已接受</label>
                                        </div>
                                        <div class="radio-item">
                                            <input type="radio" name="is_accepted" id="acceptedFalse" value="False"
                                                {% if record.is_accepted == False %}checked{% endif %}>
                                            <label for="acceptedFalse">已拒绝</label>
                                        </div>
                                        <div class="radio-item">
                                            <input type="radio" name="is_accepted" id="acceptedNone" value=""
                                                {% if record.is_accepted is None %}checked{% endif %}>
                                            <label for="acceptedNone">未处理</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 推荐内容 -->
                    <div class="form-section">
                        <h4><i class="fa fa-comment"></i> 推荐详情</h4>
                        <div class="form-row">
                            <div class="form-col">
                                <div class="form-group">
                                    <label>推荐内容 <span class="required-mark">*</span></label>
                                    <textarea name="content" class="form-control" required>{{ record.content }}</textarea>
                                </div>
                                <div class="form-group">
                                    <label>反馈内容</label>
                                    <textarea name="feedback" class="form-control">{{ record.feedback|default:'' }}</textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="btn-group">
                        <button type="button" class="btn btn-default" onclick="window.history.back();">返回</button>
                        <button type="reset" class="btn btn-default">重置</button>
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</section>
{% endblock %}